package com.gitee.mrj.aiboot.core.sf.generators.ui;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.KV;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.SFError;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SFErrorGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        SFError error = AnnotatedElementUtils.findMergedAnnotation(field, SFError.class);
        build(node, error);

    }

    @Override
    public void generate(UIForm root, Class clazz) {
        SFError error = AnnotatedElementUtils.findMergedAnnotation(clazz, SFError.class);
        build(root, error);
    }

    private void build(UIForm node, SFError error) {
        ObjectNode ui = node.getUi();
        ui.put("liveValidate", error.liveValidate());
        KV[] errors = error.errors();
        if (ArrayUtils.isNotEmpty(errors)) {
            ArrayNode arrayNode = ui.putArray("errors");
            for (KV kv : errors) {
                arrayNode.addObject().put(kv.key(), kv.value());
            }
        }

        ui.put("firstVisual", error.firstVisual());
        ui.put("onlyVisual", error.onlyVisual());
        String[] ingoreKeywords = error.ingoreKeywords();
        if (ArrayUtils.isNotEmpty(ingoreKeywords)) {
            ArrayNode arrayNode = ui.putArray("ingoreKeywords");
            for (String ingoreKeyword : ingoreKeywords) {
                arrayNode.add(ingoreKeyword);
            }
        }
        ui.put("showRequired", error.showRequired());
    }


    @Override
    public Class[] supports() {
        return new Class[]{SFError.class};
    }
}
